package gis.dao;

import bean.cityfun.AreaDimSceneType;
import bean.common.*;
import com.google.common.base.Enums;
import gis.algorithm.GeoPoint;
import gis.algorithm.GeoUtils;
import gis.algorithm.cluster.RqCluster;
import gis.common.ServiceFactory;
import gis.core.bean.KeyValue;
import gis.core.utils.CommonUtils;
import gis.service.CellSceneService;
import gis.serviceImpl.CellSceneOracleServiceImpl;
import gis.serviceImpl.CellSceneServiceImpl;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by hupeng on 16/6/7.
 */
public class CellSceneDao {
    private static Logger logger = LoggerFactory.getLogger(CellSceneDao.class);

    public List<AreaDimSceneType> GetSceneTypeList() throws Exception {
        CellSceneService service = ServiceFactory.getInstance(CellSceneService.class);
        return service.GetSceneTypeList();
    }

    public List<KeyValue> GetSceneAppTopics() throws Exception {
        CellSceneService service = ServiceFactory.getInstance(CellSceneService.class);
        return service.GetSceneAppTopics();
    }

    public List<CellDimScene> GetSceneList(String sceneTypeId, String cityId,String apptopicsid) {
        List<CellDimScene> list = new ArrayList<CellDimScene>();
        try {
            CellSceneService service = ServiceFactory.getInstance(CellSceneService.class);
            list = service.GetCellSceneList(sceneTypeId, cityId,apptopicsid);
        } catch (Exception e) {
            logger.error("获取自定义场景出错：" + e.getMessage(), e);
            e.printStackTrace();
        }
        return list;
    }

    public long AddCellDimScene(String sceneName, String rings, int ringType, String sceneTypeId, String sceneTypeName, String area_extend, String cells, String cellType, Region region, String appTopicsId, String appTopicsName) {
        int i = 0;
        long scene_id = 0;
        try {
            CellSceneService service = ServiceFactory.getInstance(CellSceneService.class);

            scene_id = Long.valueOf(gis.core.utils.CommonUtils.uuid());
            CellDimScene dimScene = new CellDimScene();
            dimScene.setScene_id(String.valueOf(scene_id));
            dimScene.setScene_type_name(sceneTypeName);
            dimScene.setRange(rings);
            dimScene.setScene_name(sceneName);
            dimScene.setScene_type_id(sceneTypeId);
            dimScene.setCityId(region.getId());
            dimScene.setCityName(region.getName());
            dimScene.setCellTypes(cellType);
            dimScene.setAppTopicsId(appTopicsId);
            dimScene.setAppTopicsName(appTopicsName);

            i = service.AddCellDimScene(dimScene);
            if (i > 0 && StringUtils.isNotEmpty(cellType)) {

                List<CellRefDimScene> refList = new ArrayList<CellRefDimScene>();

                //取得四个坐标点
                List<List<Double>> ringList = gis.core.utils.Serializer.deserializeJson(rings, new ArrayList<List<Double>>().getClass());
                List<GeoPoint> points = new ArrayList<GeoPoint>();

                Double xMin = ringList.get(0).get(0);
                Double xMax = ringList.get(0).get(0);
                Double yMin = ringList.get(0).get(1);
                Double yMax = ringList.get(0).get(1);

                for (List<Double> xy : ringList) {
                    points.add(new GeoPoint(xy.get(0), xy.get(1)));

                    if (xy.get(0) > xMax) {
                        xMax = xy.get(0);
                    }

                    if (xy.get(0) < xMin) {
                        xMin = xy.get(0);
                    }

                    if (xy.get(1) > yMax) {
                        yMax = xy.get(1);
                    }
                    if (xy.get(1) < yMin) {
                        yMin = xy.get(1);
                    }
                }


                List<Bts> btsList = GetBtsWithRings(xMin, xMax, yMin, yMax, cellType);

                if (btsList != null && btsList.size() > 0) {
                    for (Bts bts : btsList) {
                        List<Cell> cellList = bts.getCells();
                        for (Cell cell : cellList) {
                            if (GeoUtils.isPointInPolygon(points, cell.getLongitude(), cell.getLatitude())) {
                                CellRefDimScene refDimScene = new CellRefDimScene();
                                refDimScene.setScene_id(String.valueOf(scene_id));
                                refDimScene.setScene_name(sceneName);
                                refDimScene.setScene_type_id(sceneTypeId);
                                refDimScene.setScene_type_name(sceneTypeName);
                                refDimScene.setId(cell.getId());
                                refDimScene.setName(cell.getName());
                                refDimScene.setTac(cell.getTac());
                                refDimScene.setEci(cell.getEci());
                                refDimScene.setLongitude(cell.getLongitude());
                                refDimScene.setLatitude(cell.getLatitude());
                                refDimScene.setAzimuth(cell.getAzimuth());
                                refDimScene.setResType(cell.getResType());
                                refList.add(refDimScene);
                            }
                        }
                    }
                }
                //new CellSceneOracleServiceImpl().AddCellRefSceneList(refList);
                service.AddCellRefSceneList(refList);
            }

        } catch (Exception e) {
            logger.error("添加用户自定义场景出错：" + e.getMessage(), e);
            e.printStackTrace();
        }
        if (i > 0) {
            return scene_id;
        } else {
            return 0;
        }
    }

    public int DeleteCellDimScene(String id) {
        int i = 0;
        try {
            CellSceneService service = ServiceFactory.getInstance(CellSceneService.class);
            i = service.DeleteCellDimScene(id);
            service.DeleteCellRefScene(id);
        } catch (Exception e) {
            logger.error("删除用户自定义场景出错：" + e.getMessage(), e);
            e.printStackTrace();
        }

        return i;
    }

    public List<AreaDimSceneType> GetAreaDimSceneTypeList() {
        List<AreaDimSceneType> list = new ArrayList<AreaDimSceneType>();

        try {
            CellSceneService service = ServiceFactory.getInstance(CellSceneService.class);
            list = service.GetSceneTypeList();
        } catch (Exception e) {
            logger.error("获取场景分类列表出错：" + e.getMessage(), e);
            e.printStackTrace();
        }
        return list;
    }

    private List<Bts> GetBtsWithRings(double xMin, double xMax, double yMin, double yMax, String cellType) {
        List<Bts> list = null;
        try {

            RqCluster rqCluster = new RqCluster();
            rqCluster.setxMin(xMin);
            rqCluster.setxMax(xMax);
            rqCluster.setyMin(yMin);
            rqCluster.setyMax(yMax);
            rqCluster.setLevel(10);
            rqCluster.setResolution(0.00001903568804664224);
            rqCluster.setWkid(4326);

            RqCell rqCell = new RqCell();
            //rqCell.setLTE(true);
            if (null != cellType && !"".equals(cellType)) {
                if (cellType.contains("LTE")) {
                    rqCell.setLTE(true);
                }

                if (cellType.contains("TD")) {
                    rqCell.setTD(true);
                }

                if (cellType.contains("GSM")) {
                    rqCell.setGSM(true);
                }
            }

            rqCell.setAlonecell(0);
            if (rqCell.getRegion() == null) {
                Region region = new Region();
                region.setType(9000);
                region.setId("1");
                rqCell.setRegion(region);
            }
            ResCellDao dao = new ResCellDao();
            list = dao.GetBtsList(rqCell, rqCluster);
        } catch (Exception e) {
            logger.error("获取基站出错：" + e.getMessage(), e);
        }

        return list;
    }

    /**
     * 导出场景数据
     *
     * @param sceneTypeId
     * @param cityId
     * @return
     * @throws Exception
     */
    public List<CellRefDimSceneExpot> GetLExpotData(String sceneTypeId, String cityId,String appTopicsId) throws Exception {
        CellSceneService service = ServiceFactory.getInstance(CellSceneService.class);
        List<CellRefDimSceneExpot> list = service.GetLExpotData(sceneTypeId, cityId,appTopicsId);
        return list;
    }

    public List<CellRefDimScene> GetCellRefSceneList(String scene_id) throws Exception {
        CellSceneService service = ServiceFactory.getInstance(CellSceneService.class);
        return service.GetCellRefSceneList(scene_id);
    }

    public int LoadImPortSceneData(String sceneStr) throws Exception {
        String[] scenes = StringUtils.split(sceneStr, "\r\n");
        if (StringUtils.isEmpty(sceneStr) || scenes.length <= 1) {
            throw new Exception("导入数据为空");
        }
        List<CellRefDimScene> refList = new ArrayList<CellRefDimScene>();
        Map<String, CellDimScene> map_scenes = new HashMap<>();

        CellSceneService service = ServiceFactory.getInstance(CellSceneService.class);
        //加载场景类型
        List<AreaDimSceneType> types = GetSceneTypeList();
        List<AreaDimSceneType> new_types = new ArrayList<>();
        Map<String, String> map_types = new HashMap<>();
        for (AreaDimSceneType type : types) {
            map_types.put(type.getScene_type_id(), type.getScene_type_name());
        }

        CellRefDimScene cell;
        for (int i = 1; i < scenes.length; i++) {
            try {
                String scene = scenes[i].replace("\t", "").replace("\"", "");
                String[] d = StringUtils.split(scene, ",");
                cell = new CellRefDimScene();
                cell.setScene_name((d[0] + "").trim());
                cell.setScene_type_id((d[1] + "").trim());
                cell.setScene_type_name((d[2] + "").trim());
                cell.setId((d[3] + "").trim());
                cell.setName((d[4] + "").trim());
                cell.setStrCellType((d[5] + "").trim());
                cell.setTac((d[6] + "").trim());
                cell.setEci((d[7] + "").trim());
                cell.setLongitude(Double.parseDouble(d[8]));
                cell.setLatitude(Double.parseDouble(d[9]));
                cell.setAzimuth(Double.parseDouble(d[10]));
                cell.setCityId((d[11] + "").trim());
                cell.setCityName((d[12] + "").trim());

                if (!map_scenes.containsKey(cell.getScene_name())) {
                    CellDimScene cellDimScene = new CellDimScene();
                    cellDimScene.setScene_id(CommonUtils.uuid());
                    cellDimScene.setScene_name(cell.getScene_name());
                    cellDimScene.setScene_type_id(cell.getScene_type_id());
                    cellDimScene.setScene_type_name(cell.getScene_type_name());
                    cellDimScene.setCityId(cell.getCityId());
                    cellDimScene.setCityName(cell.getCityName());
                    switch (cell.getStrCellType()) {
                        case "GSMCELL":
                            cellDimScene.setCellTypes("GSM");
                            break;
                        case "TDCELL":
                            cellDimScene.setCellTypes("TD");
                            break;
                        case "LTECELL":
                            cellDimScene.setCellTypes("LTE");
                            break;
                    }
                    map_scenes.put(cell.getScene_name(), cellDimScene);
                }
                cell.setScene_id(map_scenes.get(cell.getScene_name()).getScene_id());

                if (!map_types.containsKey(cell.getScene_type_id())) {
                    new_types.add(new AreaDimSceneType(cell.getScene_type_id(), cell.getScene_type_name()));
                }
                refList.add(cell);
            } catch (Exception e) {
                throw new Exception("文件格式错误，请按照格式录入数据！");
            }

        }


        int i = 0;
        try {
            //service = new CellSceneOracleServiceImpl();
            //入库新的场景类型
            if (new_types.size() > 0) {
                service.AddSceneTypes(new_types);
            }
            //入库场景主表
            if (map_scenes.size() > 0) {
                service.AddCellDimScenes(map_scenes.values());
            }
            //入库场景明细
            if (refList.size() > 0) {
                i = service.AddCellRefSceneList(refList);
            }
        } catch (Exception e) {
            throw new Exception("数据入库错误!");
        }
        return i;
    }

}
